package spikes

import (
	"enjoy-shop/api/base"
	"enjoy-shop/formdata"
	"enjoy-shop/server/spikes"
	"fmt"
	"gitee.com/xuxinzhi2206/corehub/gopay"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

// 创建秒杀订单
func CreateOrder(c *gin.Context) {
	var data formdata.OrderInfo
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}

	//创建订单
	order, err := spikes.CreateOrder(data)
	fmt.Println("订单数据：：", order)
	if order == nil {
		base.RespData(c, nil, fmt.Errorf("秒杀订单创建失败：：%v", err))
		return
	}
	//扣减库存
	_, err = spikes.UpdateSpikesStock(data.UpdateStock)

	////事务
	//request, err := pkg.QsFireRequest(data)
	//if err != nil {
	//	base.RespData(c, nil, err)
	//	return
	//}
	//fmt.Println("事务消息", request)

	//判断返回结果
	if err != nil {
		base.RespData(c, nil, err)
	} else {
		//转字符串
		newPayData := gopay.NewPayData()
		url, err := newPayData.Pay(&gopay.PayData{
			OutTradeNo:  order.OrderNo,
			TotalAmount: order.Amount,
			Subject:     "秒杀测试订单支付***",
			ReturnUrl:   viper.GetString("return_url"),
			NotifyUrl:   viper.GetString("pay"),
		})

		ss := formdata.SpikesOrderInfo{
			OrderNo: order.OrderNo,
			Url:     url,
		}
		//判断返回结果
		base.RespData(c, ss, err)
	}
}
